<template>
	<view class="user_content">
		<u-navbar title="通士达导航" leftIcon=" " bgColor="#ffffff" :placeholder="true" :fixed="true">
			<!-- <view slot="left" class="col-4">
				<view @click="handleOpenpicker">{{areaData?areaData:'选择区域地址'}}</view>
			</view> -->
		</u-navbar>

		<map ref="map" id="map" :style="'height:' + mapHeight + 'px'" style="width: 100%;" :scale="12"
			:latitude="latitude" :longitude="longitude" :show-compass="true" :show-location="true"
			@callouttap="dpcdetail" @markertap="dpcdetail" :markers="covers" @regionchange="bindregionchange">
			<!-- <cover-view slot="callout">
        <cover-view class="customCallout position-relative" v-for="(item,i) in covers" :key="i" :marker-id="item.id">
          <cover-view class="rounded-10 p-1" :class="item.id==mapMarkerId?'active':'unactive'">
            <cover-view class="flex a-center j-start ">
              <cover-view class="font-bold">{{item.title}}</cover-view>
            </cover-view>
          </cover-view>
          <cover-view class="san">
            <cover-image v-if="mapMarkerId!=item.id" :src="imageServe+'kgs1.png'" class="svgsmallkg"></cover-image>
            <cover-image v-if="mapMarkerId==item.id" :src="imageServe+'kgs.png'" class="svgsmallkg"></cover-image>
          </cover-view>
        </cover-view>
      </cover-view> -->
		</map>
		<cover-image v-if="!isScroll" class="localtion-center-icon" src="/static/images/local-center.png"
			@click="dingwei"></cover-image>

		<!-- 底部弹-->
		<view class="store-box-flex bg-light-2 shadow" :style="{'bottom':'0px'}" @touchstart="handleTouchStart"
			@touchcancel="handleTouchCancel" @touchend="handleTouchEnd">
			<view @click.stop="handleOpen" class="line-box relative">
				<view class="p-1"></view>
				<view class="line"></view>
				<view class="text-center font-26 absolute-auto text-primary font-weight">{{!isScroll?'点击展开':'点击收起'}}
				</view>
			</view>
			<view class="px-2 py-3 bg-white">
				<view @click="handleOpenpicker">{{areaData?areaData:'选择区域地址'}}</view>
			</view>
			<scroll-view :scroll-y="isScroll" class="store-box-view" :class="{'scroll':isScroll}"
				:style="{'height':height + 'px'}" @scrolltolower="scrollView" :lower-threshold="100">
				<view class="store-box" :class="item.id==mapMarkerId?'active':'unactive'" v-for="(item,index) in covers"
					:key="index" @click="handleItem(item)">
					<view class="flex mb-2">
						<image :src="imageServe+'cl.png'" class="charge-empty-icon"></image>
						<view class="ml-1 flex-1">
							<view class="flex j-sb">
								<view class="font-bold font-32 flex-1 mr-3 ml-1">{{item.repairName}}</view>
								<view class="flex  j-start mt-1">
									<image :src="imageServe+'nav.png'" class="nav-icon1"></image>
									<view class="font-26">{{item.distance}}KM</view>
								</view>
							</view>
						</view>
					</view>
					<view class="flex-start mb-2">
						<u-icon name="phone-fill" color="#999" size="15"></u-icon>
						<view class="ml-2 font-28">{{item.telphone}}</view>
					</view>
					<view class="flex-start">
						<u-icon name="map-fill" color="#999" size="15"></u-icon>
						<view class="font-24 text-secondary ml-2 flex-1">{{item.address}}</view>
					</view>

				</view>
				<view class="p-2 text-center text-secondary font-26" v-if="isLoadMore&&covers.length!==0">--没有更多数据了--
				</view>
				<u-empty mode="data" v-if="covers.length==0" text='暂无数据'
					icon="https://www.banlift.com/oss/app/data.png"></u-empty>
			</scroll-view>
		</view>


		<u-popup :show="showPopup" @close="showPopup=false" mode="center" round="20" :closeable="false">

			<view class="col-10 bg-white rounded-15 p-4 relative">

				<view class="flex-start mb-3 mt-2">
					<image :src="imageServe+'cl.png'" class="svg40 mr-1"></image>
					<view class="font-bold font-32">{{shopMainObj.repairName}}</view>
				</view>
				<view class="flex-start mb-3">
					<u-icon name="phone-fill" color="#999" size="15"></u-icon>
					<view class="ml-2 font-28">{{shopMainObj.telphone}}</view>
				</view>
				<view class="flex-start mb-4">
					<u-icon name="map-fill" color="#999" size="15"></u-icon>
					<view class="font-24 text-secondary ml-2 flex-1">{{shopMainObj.address}}</view>
				</view>
				<view class="flex-around  pt-3 border-top">
					<view class="h-70 rounded-10 bg-primary text-white col-3 flex-center"
						@click="handleCall(shopMainObj)">拨打电话</view>
					<view class="h-70 rounded-10 bg-primary text-white col-3 flex-center"
						@click="openLocation(shopMainObj)">开始导航</view>
				</view>
				<view @click="showPopup=false" class="flex j-center a-center absolute w100 left-0"
					style="bottom: -80rpx;">
					<u-icon name="close-circle-fill" color="#fff" size="26"></u-icon>
				</view>
			</view>
		</u-popup>

		<uni-region-sheet :showSheetView="showSheetView" displayStyle="sheet" :defaultIndexs="[0,0,0]"
			@onSelected="bindPickerChange"></uni-region-sheet>

		<loginView ref="loginViewRefs" />
	</view>
</template>
<script>
	import loginView from '../login/index.vue'
	import {
		repairList,
		cityList,
		addressByLocation
	} from '@/api/repair.js'
	import {
		loGetLocation,
		setLocationMap,
		deWeight
	} from "@/utils/index.js";
	import {
		mapState,
		mapMutations
	} from "vuex";
	import uniRegionSheet from '@/components/zxp-uniRegionSheet/zxp-uniRegionSheet.vue'
	const positions = [{
			latitude: 31.8512435,
			longitude: 117.2606134,
			id: 123,
			title: "国祯广场站",
		},
		{
			latitude: 31.8422784,
			longitude: 117.220615435,
			id: 345,
			title: "惠州广场站",
		}, {
			latitude: 31.7922764,
			longitude: 117.210615435,
			id: 3340,
			title: "徽州大道广场站",
		},
		{
			latitude: 31.7922764,
			longitude: 117.210615435,
			id: 3400,
			title: "徽州大道广场站",
		}, {
			latitude: 31.7922764,
			longitude: 117.210615435,
			id: 4340,
			title: "徽州大道广场站",
		}, {
			latitude: 31.7922764,
			longitude: 117.210615435,
			id: 3140,
			title: "徽州大道广场站",
		}, {
			latitude: 31.7922764,
			longitude: 117.210615435,
			id: 3420,
			title: "徽州大道广场站",
		},
	];
	export default {
		components: {
			uniRegionSheet,
			loginView
		},
		computed: {
			...mapState(["userInfo", "locateInformation"]),
		},
		data() {
			return {
				showMapBox: true,
				id: 0,
				latitude: "",
				longitude: "",
				covers: [],
				detail: [],
				mapScale: 9,
				mapHeight: 300,
				height: 200,
				maxHeight: 0,
				isScroll: false,
				middleHeight: 200,
				bottom: 50,
				safeAreaInsetsHeight: 0,
				// --
				minOffset: 30, ////最小偏移量，低于这个值不响应滑动处理
				minTime: 60, //最小时间，单位：毫秒，低于这个值不响应滑动处理
				startX: 0, //开始时的X坐标
				startY: 0, //开始时的Y坐标
				startTime: 0, //开始时的毫秒数

				mapMarkerId: "",

				shopMainObj: {},
				showPopup: false,
				showSheetView: false,
				areaData: '',
				query: {
					latitude: 31.820605,
					longitude: 117.227105,
					districtCode: '',
					cityCode: '',
					pageSize: 10,
					pageNum: 1,
				},
				isLoadMore: false

			};
		},
		onPageScroll(e) {},
		async onLoad() {
			await this.$onLaunched;


			this.safeAreaInsetsHeight = this.systemInfo.windowHeight
			// this.maxHeight = this.safeAreaInsetsHeight - 300;

			this.bottom = this.systemInfo.safeAreaInsets.bottom;
			this.mapHeight = this.safeAreaInsetsHeight - this.height - this.bottom - 150;
			await setLocationMap(async (res) => {
				this.query.latitude = res.latitude;
				this.query.longitude = res.longitude;
				this.latitude = res.latitude;
				this.longitude = res.longitude;
				await this.getaddressByLocation();

			}, f => {
				this.getlist();
			});
		},
		async onShow() {},
		onPullDownRefresh() {
			setTimeout(function() {
				uni.stopPullDownRefresh();
			}, 500);
		},
		//分享
		onShareAppMessage() {
			wx.showShareMenu({
				withShareTicket: true,
				menus: ["shareAppMessage", "shareTimeline"],
			});
		},
		methods: {
			getaddressByLocation() {
				addressByLocation({
					longitude: this.query.longitude,
					latitude: this.query.latitude
				}).then(res => {
					// this.areaData = res.data.city + '-' + res.data.district;
					this.areaData = res.data.city + '-' + '全区域';
					// this.query.districtCode = res.data.adcode;
					this.query.cityCode = res.data.adcode ? res.data.adcode.substring(0, 4) : '';
					this.getlist();
				})
			},
			handleOpenpicker() {
				this.showSheetView = true
			},
			bindPickerChange(row) {
				if (row.confirm) {
					this.areaData = row.data.city + '-' + row.data.area;
					this.query.districtCode = row.data.aCode;
					this.query.cityCode = row.data.cCode;
				}
				console.log(row)
				this.covers = []
				this.showSheetView = false;
				this.isLoadMore = false;
				this.query.pageNum = 1;
				this.getlist();

			},
			dpcdetail(e) {
				this.mapMarkerId = e.detail.markerId;
				this.covers = this.moveToTop(this.covers, this.mapMarkerId);

				const {
					markerId
				} = e.detail;
				const marker = this.covers.find((m) => m.id === markerId);
				marker && this.moveMarkerToCenter(marker);
				console.log(e, '----')
			},
			//数组对象，指定的对象置顶
			moveToTop(arr, id) {
				const index = arr.findIndex(obj => obj.id === id);
				if (index !== -1) {
					const item = arr.splice(index, 1)[0];
					arr.unshift(item);
				}
				return arr;
			},
			moveMarkerToCenter(marker) {
				//将marker移动至中心点
				uni.createMapContext("map", this).moveToLocation({
					longitude: marker.longitude,
					latitude: marker.latitude,
					success: (res) => {
						const timer = setTimeout(() => {
							this.longitude = marker.longitude;
							this.latitude = marker.latitude;
							clearTimeout(timer);
							//进行缩放，设置为16
							this.scale = 16;
						}, 300);
					},
				});
			},

			handleOpen() {
				if (this.isScroll) {
					console.log("向下滑动");
					this.height = this.middleHeight;
					this.isScroll = false;
					this.mapHeight = this.safeAreaInsetsHeight - this.height - this.bottom - 100;
				} else {
					console.log("向上滑动");
					this.isScroll = true;
					this.height = this.safeAreaInsetsHeight * 0.6;
					setTimeout(() => {
						this.mapHeight = this.safeAreaInsetsHeight - this.height - this.bottom - 100;
					}, 1000);
				}
			},

			bindregionchange(e) {
				uni.createMapContext("map", this).getScale({
					success: (res) => {
						this.mapScale = res.scale;
					},
				});
				uni.createMapContext("map", this).includePoints({
					success: (res) => {},
				});
			},

			getlist() {
				repairList(this.query).then(res => {
					if (res.rows.length == 0) {
						let oldLoad = {}
						this.isLoadMore = true;
						oldLoad = Object.assign({}, this.query);
						oldLoad.pageNum = this.query.pageNum;
						this.query = oldLoad
						this.$forceUpdate()
						return
					}
					this.isLoadMore = false;
					let oldList = this.covers || []
					if (this.query.pageNum == 1) {
						oldList = res.rows
					} else {
						oldList.push(...res.rows)
					}
					if (oldList.length > 0) {
						this.covers = oldList.map((p, i) => {
							return {
								...p,
								id: i + 1,
								latitude: p.latitude,
								longitude: p.longitude,
								joinCluster: true, // 指定了该参数才会参与聚合
								title: p.repairName,
								width: 15,
								height: 26,
								callout: {
									content: p.repairName,
									color: '#ffffff',
									fontSize: 12,
									borderRadius: 4,
									bgColor: '#409EFF',
									padding: 6,
									display: 'ALWAYS',
								},
							};
						});
						this.covers = deWeight(this.covers, 'repairId')
					} else {
						this.covers = []
					}
				})

			},
			scrollView(e) {
				if (!this.isLoadMore) {
					this.isLoadMore = true;
					this.query.pageNum += 1;
					this.getlist();
				}
			},


			handleItem(item) {
				if (uni.getStorageSync('token')) {
					this.showPopup = true;
					this.shopMainObj = item;
					this.mapMarkerId = item.id;
					this.moveMarkerToCenter(item);
				} else {
					this.$refs.loginViewRefs.open();
				}

			},
			openLocation(row) {
				uni.openLocation({
					name: row.repairName,
					latitude: row.latitude,
					longitude: row.longitude,
					success: function() {},
				});
			},
			handleCall(item) {
				uni.makePhoneCall({
					phoneNumber: item.telphone
				})
			},
			//点击定位到当前位置
			dingwei() {
				setLocationMap((res) => {
					this.latitude = res.latitude;
					this.longitude = res.longitude;
					uni.createMapContext("map", this).moveToLocation({
						latitude: this.latitude,
						longitude: this.longitude,
					});

				}, f => {});

			},

			handleTouchStart(e) {
				// this.startY = event.changedTouches[0].clientY;
				this.startX = e.touches[0].pageX; // 获取触摸时的x坐标
				this.startY = e.touches[0].pageY; // 获取触摸时的x坐标
				this.startTime = new Date().getTime(); //获取毫秒数
			},
			handleTouchCancel() {
				this.startX = 0; //开始时的X坐标
				this.startY = 0; //开始时的Y坐标
				this.startTime = 0; //开始时的毫秒数
			},

			handleTouchEnd(e) {
				var endX = e.changedTouches[0].pageX;
				var endY = e.changedTouches[0].pageY;
				var touchTime = new Date().getTime() - this.startTime; //计算滑动时间
				//开始判断
				//1.判断时间是否符合
				if (touchTime >= this.minTime) {
					//2.判断偏移量：分X、Y
					var xOffset = endX - this.startX;
					var yOffset = endY - this.startY;
					// console.log('xOffset', xOffset)
					// console.log('yOffset', yOffset)
					//①条件1（偏移量x或者y要大于最小偏移量）
					//②条件2（可以判断出是左右滑动还是上下滑动）
					if (
						Math.abs(xOffset) < Math.abs(yOffset) &&
						Math.abs(yOffset) >= this.minOffset
					) {
						//上下滑动
						//③条件3（判断偏移量的正负）
						if (yOffset < 0 || e.target.offsetTop > 100) {
							console.log("向上滑动", e.target.offsetTop);
							this.isScroll = true;
							this.height = this.safeAreaInsetsHeight * 0.6;
							setTimeout(() => {
								this.mapHeight = this.safeAreaInsetsHeight - this.height - this.bottom - 100;
							}, 1000);

						} else {
							console.log("向下滑动", e.target.offsetTop);
							this.height = this.middleHeight;
							this.isScroll = false;
							this.mapHeight = this.safeAreaInsetsHeight - this.height - this.bottom - 100;
						}
					}
				} else {
					console.log("滑动时间过短", touchTime);
				}
			},
		},
	};
</script>
<style lang="scss" scoped>
	.logo {
		width: 400rpx;
		height: 60rpx;
	}

	.swiper-wrap {
		height: 220rpx;
		position: relative;

		&::after {
			content: "";
			height: 180rpx;
			background-color: #ffe000;
			width: 100%;
			position: absolute;
			left: 0;
			top: 0;
		}

		.swiper {
			position: relative;
			z-index: 2;
			height: 100%;
			width: 700rpx;
			margin: auto;

			.img {
				height: 100%;
				border-radius: 4px;
			}
		}
	}

	.map {
		position: relative;
	}

	.localtion-center-icon {
		position: fixed;
		right: 30rpx;
		top: 25%;
		height: 90rpx;
		width: 90rpx;
		z-index: 9;
	}

	.store-box-flex {
		background-color: #f5f5f5;
		border-radius: 10px 10px 0 0;
		padding: 0 20rpx 50rpx;
		position: fixed;
		bottom: 50px;
		left: 0;
		width: 100%;
		box-sizing: border-box;
		overflow: hidden;
		z-index: 100;

		.store-box-view {
			transition: ease 0.7s all;
		}

		.scroll {
			overflow-y: scroll;
		}

		.line-box {
			box-sizing: border-box;
			padding: 20rpx;

			.line {
				margin: auto;
				width: 150rpx;
				height: 10rpx;
				border-radius: 20px;
				background-color: #e1e1e1;
			}
		}

		.store-box {
			background-color: #fff;
			border-radius: 10rpx;
			padding: 20rpx;
			box-sizing: border-box;
			width: 100%;
			margin-bottom: 20rpx;

			.title {
				position: relative;
				font-size: 32rpx;

				&:after {
					content: "";
					position: absolute;
					bottom: 2rpx;
					left: 0rpx;
					right: 0rpx;
					height: 2px;
					border-radius: 4px;
					background: rgba(255, 224, 0, 0.8);
				}
			}

			&.unactive {
				background: #fff;
				border: 2px solid #fff;
			}

			&.active {
				background: #409eff26;
				border: 2px solid #409eff26;
			}

			.charge-empty-icon {
				height: 40rpx;
				width: 40rpx;
			}

			.nav-icon1 {
				width: 36rpx;
				height: 36rpx;
				margin-right: 10rpx;
			}

			.nav-icon {
				width: 60rpx;
				height: 60rpx;
			}




		}
	}
</style>